#!/usr/bin/perl
#     Xepec.ru - социальная сеть
#     Copyright (C) 2008  Fedorchenko Alexander
#
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#     Autor: Fedorchenko Alexander
#     Mail: sos20@list.ru
#     Date: 12/12/2009

sub music_count
{
	$ath = $dbcnx->prepare(qq{SELECT id FROM music WHERE users_id=$_[0]});
	$ath->execute();
	$res = $ath->rows();
	return $res;
	
	
}

sub ogg_tag_read
{
	my $ogg_file = shift;
	
		my $ogg = Ogg::Vorbis::Header->new($ogg_file);
			while (my ($k, $v) = each %{$ogg->info}) {
				print "$k: $v<br/>";
			}
			print "<br />";
			foreach my $com ($ogg->comment_tags) {
				print "$com: $_<br/>" foreach $ogg->comment($com);
			}
}

sub mp3_tag_read
{
	# use module
	use MP3::Tag;

	# set filename of MP3 track
	$filename = shift;

	# create new MP3-Tag object
	$mp3 = MP3::Tag->new($filename);
	$mp3->get_tags();

	# if ID3v2 tags exists
	if (exists $mp3->{ID3v2})
	{
		# get a list of frames as a hash reference
		$frames = $mp3->{ID3v2}->get_frame_ids();

		# iterate over the hash
		# process each frame
		foreach $frame (keys %$frames) 
		{
			# for each frame
			# get a key-value pair of content-description
			($value, $desc) = $mp3->{ID3v2}->get_frame($frame);
		
			#print "$frame $desc: ";
		
		
			# sometimes the value is itself a hash reference containing more values
			# deal with that here
			if (ref $value)
			{
				while (($k, $v) = each (%$value))
				{
					print "\n     - $k: $v";
				}
				print "\n";
			}
			else
			{
				#print "$value\n";
				#print $frame."\t".$value."</br>";
				$hash{$frame} = $value;
			}
		#print $frame.$value;
		}
	}
	$mp3->close();
	return %hash;
}

sub db_tag_edit
{
	
	my $file_id = shift;
	
	my $title = shift;
	my $artist = shift;
	my $album = shift;
	my $year = shift;
	my $ganre = shift;
	my $track = shift;
	
	use CGI::Cookie;
	%cookies = fetch CGI::Cookie;
	$nic_cook = $cookies{'xepec_nic'}->value;
	$pass_cook = $cookies{'xepec_pass'}->value;
	
	$re = $dbcnx->prepare(qq{SELECT id FROM reg WHERE name=? and md5=?});
	$re->execute($nic_cook,$pass_cook);
	$numrows = $re->rows;
	$id = $re->fetchrow_array();
	if ($numrows == 1)
	{
		$dbcnx->do(qq{UPDATE music SET title='$title', artist='$artist',album='$album', year='$year', ganre='$ganre', track='$tr_no' WHERE id="$file_id" });
		
		$re->finish();
		$dbcnx->disconnect();
		return 1;
	}
	else
	{
		return 0;
	}
}

sub db_tag_read
{
	$ath = $dbcnx->prepare(qq{SELECT * FROM music WHERE id=?});
	$ath->execute($_[0]);
	@arr_list = $ath->fetchrow_array();
	return @arr_list;
	
	
}

sub print_xml_tags
{
	use POSIX qw(ceil floor);
	
	## Более быстрый варриант возврашять print @return
	$ath = $dbcnx->prepare(qq{SELECT * FROM music WHERE users_id=? AND state=2});
	$ath->execute($_[0]);
	my $numrows = $ath->rows();
	if ($numrows > 0)
	{
		
		#$return = $return."<pl>\n";
			while(my @arr_list = $ath->fetchrow_array() )
 				{
					$file = "$DOC_ROOT/usr/$_[0]/music/@arr_list[0].ogg";
					$size = -s($file); 
					# Получили размер файла в байтах начнем конвертировать в мегабайты
					$size = $size/1024/1024;
					$size =$size*100;
					$size = floor($size);
					$size =$size/100;
					
 					push @return, qq{\t<item url="$SITE_ADDR/usr/$_[0]/music/@arr_list[0].ogg" size="$size" title="@arr_list[2]" artist="$arr_list[3]" album="@arr_list[4]" year="$arr_list[5]" ganre="$arr_list[6]" track="$arr_list[7]" />\n};
 				}
		#$return = $return."</pl>\n";
		print @return;
		#return $return;
	}
	else
	{
	return 0;
	}
}

sub file_save
{
	require "../config.pl";
	require "../core.pl";
	
	use CGI;
	use CGI::Carp qw ( fatalsToBrowser );
	use File::Basename;
	
	$CGI::POST_MAX = 1024 * 15000;
	
	my $query = new CGI;
	
	my $file_post_name = shift;
	my $auth_id = do_check;
	
	my $re = $dbcnx->prepare(qq{SELECT id FROM music});
	$re->execute();
	my $numrows = $re->rows;
	my $file_id = $numrows + 1;
	
	my $file = $query->upload($file_post_name);
	
	if(!$file)
	{
		print qq{<ets tt="numrows" />};
		return 0;
	}
	else
	{
		###
		# Определения типа файла
		###
		my $filename = "$DOC_ROOT/usr/$auth_id/music/$file_id.mp3";
		open(FILE, ">$DOC_ROOT/usr/$auth_id/music/$file_id.mp3") or die $!;
		while(<$file>) {
			print FILE $_;
		}
	
		my %mp3_tag_hash = mp3_tag_read($filename);
			my $artist = $mp3_tag_hash{"TPE1"};
			my $album = $mp3_tag_hash{"TALB"};
			my $title = $mp3_tag_hash{"TIT2"};
			my $date = $mp3_tag_hash{"TYER"};
			my $ganre = $mp3_tag_hash{"TCON"};
			my $tr_no = $mp3_tag_hash{"TRCK"};
		print $artist;
		$dbcnx->do(qq{INSERT INTO music VALUES(0,$auth_id,'$title','$artist','$album','$date','$ganre','$tr_no',0)});
		$re->finish();
		$dbcnx->disconnect();
	
		open (FILE, '-|', "$DOC_ROOT/music/lib_upload.pl");
		
		#my $pid = fork();
		#if($pid)
		#{
		#	exec("$DOC_ROOT/music/lib_upload.pl");
		#}
		
		return $file_id;
	}
}

1;

